//
//  WDAdjustManager.m
//  WDPolymerizeSDK
//
//  Created by little People on 2023/6/12.
//

#import "WDAdjustManager.h"
#import "WDCallBack.h"
#import "WDThinkingManager.h"
#import "WDJsonManager.h"

#ifdef DEBUG//调试状态，打开LOG功能
#define environment1 ADJEnvironmentSandbox
#else//发布状态，关闭LOG功能
#define environment1 ADJEnvironmentProduction
#endif

@interface WDAdjustManager ()<AdjustDelegate>
@property (nonatomic, strong)NSTimer *adjustTimer;
@end
@implementation WDAdjustManager
static WDAdjustManager *_AdjustManager = nil;
+ (instancetype)shareAdjustManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _AdjustManager = [[self alloc] init];
        
    });
    return _AdjustManager;
}

- (void)adjustConfig
{
    NSString *yourAppToken = [WDJsonManager adjustTokenForSDKConfigFile];
    NSString *environment = ADJEnvironmentProduction;
    ADJConfig *adjustConfig = [ADJConfig configWithAppToken:yourAppToken
                                      environment:environment allowSuppressLogLevel:true];
    [adjustConfig setLogLevel:ADJLogLevelVerbose];
    adjustConfig.delegate = self;
    [Adjust appDidLaunch:adjustConfig];
    self.adjustTimer = [NSTimer scheduledTimerWithTimeInterval:8 target:self selector:@selector(adjustTimeout:) userInfo:nil repeats:NO];
}

- (void)adjustAttributionChanged:(ADJAttribution *)attribution {
    [self.adjustTimer invalidate];
    self.adjustTimer = nil;
    self.adjustCampaign = attribution.campaign?attribution.campaign:@"organic";
    
    NSString *creative = attribution.creative;
    if (creative.length > 0)
    {
        NSArray *array = [creative componentsSeparatedByString:@"_"];
        if (array.count > 0)
        {
            self.adjustCreative = [NSString stringWithFormat:@"%@",array.lastObject];
        }else{
            self.adjustCreative = @"organic";
        }
    }else{
        self.adjustCreative = @"organic";
    }
    [[NSUserDefaults standardUserDefaults] setObject:self.adjustCampaign forKey:@"w_campaign"];
    [[NSUserDefaults standardUserDefaults] setObject:self.adjustCreative forKey:@"w_creative"];
    
    [[WDThinkingManager shareThinkingManager] thinkingUser_setOnceWithKey:@"w_campaign" value:self.adjustCampaign];
    [[WDThinkingManager shareThinkingManager] thinkingUser_setOnceWithKey:@"w_creative" value:self.adjustCreative];
    
    if (self.adjustCallBackBlcok)
    {
        self.adjustCallBackBlcok(YES);
    }
}

- (void)adjustTimeout:(NSTimer *)timer
{
    [self.adjustTimer invalidate];
    self.adjustTimer = nil;
    if (self.adjustCallBackBlcok)
    {
        self.adjustCallBackBlcok(NO);
    }
}

- (void)adjustEvent:(ADJEvent *)event
{
    [Adjust trackEvent:event];
}

- (void)adjustCustomEventWithCustomId:(NSString *)cid
{
    if (cid.length > 0)
    {
        ADJEvent *event = [ADJEvent eventWithEventToken:[WDJsonManager adjustTokenForSDKConfigFile]];
        [event setCallbackId:cid];
        [Adjust trackEvent:event];
    }
    
}

@end
